package systematic.algorithm.bit;

/**
 * 不用额外变量交换两个数
 * 
 * @author lisy
 */
public class Swap {

	public static void swap(int[] arr, int i, int j) {
		arr[i] = arr[i] ^ arr[j];
		arr[j] = arr[i] ^ arr[j];
		arr[i] = arr[i] ^ arr[j];
	}
	
	public static void main(String[] args) {
		int a = 16;
		int b = 603;
		System.out.println(a + " , " + b);
		a = a ^ b;
		b = a ^ b;
		a = a ^ b;
		System.out.println(a + " , " + b);

		int[] arr = { 3, 1, 100 };
		int i = 0;
		int j = 1;
		System.out.println(arr[i] + " , " + arr[j]);
		arr[i] = arr[i] ^ arr[j];
		arr[j] = arr[i] ^ arr[j];
		arr[i] = arr[i] ^ arr[j];
		System.out.println(arr[i] + " , " + arr[j]);

		// 前提条件：需要两个不同的内存空间，否则会变成 0
		System.out.println(arr[0] + " , " + arr[2]);
		swap(arr, 0, 0);
		System.out.println(arr[0] + " , " + arr[2]);
	}
}
